package sk.hackcraft.multibox.android;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class RegistrationActivity extends Activity
{
	public static final int SUCCESS = 1;
	
	private NetService netService;
	
	private LocalBroadcastManager localBroadcastManager;
	private BroadcastReceiver broadcastReceiver;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		Intent intent = new Intent(this, NetService.class);

		bindService(intent, serviceConnection, 0);
		
		localBroadcastManager = LocalBroadcastManager.getInstance(this);
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(NetService.REGISTRATION_RESULT);
		
		broadcastReceiver = new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context context, Intent intent)
			{
				if (intent.getAction().equals(NetService.REGISTRATION_RESULT))
				{
					if (intent.getBooleanExtra("success", false))
					{
						RegistrationActivity.this.setResult(SUCCESS);
						finish();
					}
					else
					{
						Toast.makeText(RegistrationActivity.this, R.string.registration_failed_message, Toast.LENGTH_LONG).show();
					}
				}
			}
		};
		
		localBroadcastManager.registerReceiver(broadcastReceiver, filter);
		
		setContentView(R.layout.registration);
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		
		localBroadcastManager.unregisterReceiver(broadcastReceiver);
		
		unbindService(serviceConnection);
	}
	
	public void register(View view)
	{
		String name, password;
		
		EditText idView = (EditText)findViewById(R.id.name);
		EditText passwordView = (EditText)findViewById(R.id.password);
		
		name = idView.getText().toString();
		password = passwordView.getText().toString();
		
		netService.register(name, password);
	}
	
	private ServiceConnection serviceConnection = new ServiceConnection()
	{
		@Override
		public void onServiceDisconnected(ComponentName name)
		{
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service)
		{
			netService = ((NetService.NetServiceBinder)service).getService();
		}
	};
}
